package com.jsmile.cloud.tradecenter.order.listener;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.jsmile.cloud.tradecenter.api.constants.TradeConstants;
import com.jsmile.cloud.tradecenter.api.res.ResOrder;
import com.jsmile.cloud.tradecenter.api.to.OrderStatusChangeTo;
import com.jsmile.cloud.tradecenter.order.event.OrderCreateEvent;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单创建---延时关闭订单（15分钟后关闭订单）
 */
@Slf4j
@Component
public class OrderOvertimeListener {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Async
    @Order
    @EventListener(OrderCreateEvent.class)
    public void orderStatusChange(OrderCreateEvent event) {
        log.info("订单创建发送延时队列取消订单：{}", JSON.toJSONString(event.getOrder()));
        ResOrder resOrder = BeanUtil.toBean(event.getOrder(), ResOrder.class);
        resOrder.setOrderNo(event.getOrder().getId());
        OrderStatusChangeTo orderStatusChangeTo = OrderStatusChangeTo.builder().order(resOrder).orderStatus(event.getOrder().getOrderStatus()).build();
        amqpTemplate.convertAndSend(TradeConstants.TradeMq.ORDER_OVERTIME_TTL_EXCHANGE, TradeConstants.TradeMq.ORDER_OVERTIME_TTL_ROUTE, orderStatusChangeTo, message -> {
            message.getMessageProperties().setExpiration(String.valueOf(1000 * 60 * 15));// 15分钟后关闭订单
            return message;
        });
    }

}
